package com.media.appmedia.activity;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.media.appmedia.R;
import com.media.appmedia.base.BaseApplication;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;

/**
 * 
 * <pre>
 * 业务名:
 * 功能说明: 签到进入页面，实现Activit跳转，抽奖
 * 编写日期:	2014-10-22
 * 作者:	 Rose
 * 
 * 历史记录
 * 1、修改日期：
 *    修改人：
 *    修改内容：
 * </pre>
 */
public class PromotionRichActivity extends Activity {

	private int[] StartUp = { 500, 400, 300, 180 };// 启动,数量5个不能变
	private int[] Moreover = { 150, 320, 550, 800 };// 减速，数量4个不能变
	private int[] Finish = { 900 };// 结束，数量1个不能变
	private ImageView fruit_1, fruit_2, fruit_3, fruit_4, fruit_5, fruit_6,
			fruit_7, fruit_8, fruit_9, fruit_10, fruit_11, fruit_12;
	private ImageButton start_btn;
	private int image_num = 12;// 用于滚动的图片数量
	private boolean scrolling = false;
	private int fruit = 0;// 网络请求的中奖结果
	private static final int CHANGIMAGE = 0;
	private static final int CHANGSTARTBUT = 1;
	private int fruit1 = 9;// 一等奖对应的图片编号
	private int fruit2 = 1;// 二等奖对应的图片编号
	private int fruit3 = 4;// 三等奖对应的图片编号
	private int sum = 0;// 用于计数
	private RadioGroup award_group;
	// 用于音乐特效
	private SoundPool sp; // 得到一个声音池引用
	private HashMap<Object, Object> spMap; // 得到一个map的引用
	private ChangeThread changeThread;// 可控线程
	// Dialog提示信息
	private String hint;
	private int finaId;
	private String rMB;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.promotionrich_layout);
		initView();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (changeThread != null) {
			changeThread.stopThread();// 停止线程
		}
	}

	/**
	 * 开始处理
	 */
	public void initView() {
		fruit_1 = (ImageView) findViewById(R.id.fruit_1);
		fruit_2 = (ImageView) findViewById(R.id.fruit_2);
		fruit_3 = (ImageView) findViewById(R.id.fruit_3);
		fruit_4 = (ImageView) findViewById(R.id.fruit_4);
		fruit_5 = (ImageView) findViewById(R.id.fruit_5);
		fruit_6 = (ImageView) findViewById(R.id.fruit_6);
		fruit_7 = (ImageView) findViewById(R.id.fruit_7);
		fruit_8 = (ImageView) findViewById(R.id.fruit_8);
		fruit_9 = (ImageView) findViewById(R.id.fruit_9);
		fruit_10 = (ImageView) findViewById(R.id.fruit_10);
		fruit_11 = (ImageView) findViewById(R.id.fruit_11);
		fruit_12 = (ImageView) findViewById(R.id.fruit_12);
		start_btn = (ImageButton) findViewById(R.id.imageButtonwoyaochou);
		start_btn.setOnClickListener(clicklistener);
		// initSoundPool(); //初始化声音池
	}

	// public void initSoundPool(){ //初始化声音池
	// sp=new SoundPool(5,AudioManager.STREAM_MUSIC,0);
	// //maxStreams参数，该参数为设置同时能够播放多少音效//srcQuality参数，该参数设置音频文件的质量，目前还没有效果，设置为0为默认值。//streamType参数，该参数设置音频类型，在游戏中通常设置为：STREAM_MUSIC
	// spMap=new HashMap<Object, Object>();
	// spMap.put(1, sp.load(this, R.raw.ogg4956_2,1));
	// spMap.put(2, sp.load(this, R.raw.complete,1));
	// }
	//
	// public void playSound(int sound,int number){
	// //播放声音,参数sound是播放音效的id，参数number是播放音效的次数
	// AudioManager
	// am=(AudioManager)this.getSystemService(AUDIO_SERVICE);//实例化AudioManager对象
	// float audioMaxVolumn=am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	// //返回当前AudioManager对象的最大音量值
	// float
	// audioCurrentVolumn=am.getStreamVolume(AudioManager.STREAM_MUSIC);//返回当前AudioManager对象的音量值
	// float volumnRatio=audioCurrentVolumn/audioMaxVolumn;
	// sp.play((Integer) spMap.get(sound),volumnRatio,volumnRatio,1,number,1);
	// }

	OnClickListener clicklistener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			start_btn.setEnabled(false);
			scrolling = true;
			new Thread() {// 获取中奖结果
				public void run() {
					try {
						sleep(3000);// 模拟网络请求
						// fruit=check_group_select();//模拟中奖信息
						scrolling = false;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				};
			}.start();
			changeThread = new ChangeThread();// 让图片按照指定位置停止
			changeThread.start();
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@SuppressLint("HandlerLeak")
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case CHANGIMAGE:
				// playSound(1,0);
				Bundle bundle = msg.getData();
				ChangeImage(bundle.getInt("imageid"));
				break;
			case CHANGSTARTBUT:
				start_btn.setEnabled(true);
				// 等于八元时调到下一个
				if (finaId == 4) {
					ChangeImage(4 + 1);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				// 5角
				if (finaId == 0) {
					ChangeImage(0 + 1);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				// 一元
				if (finaId == 3) {
					ChangeImage(3 + 1);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				BaseApplication.getApplication().setIsSign(0);
				// 此处对中奖结果进行处理
				AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(
						PromotionRichActivity.this);
				alertbBuilder
						.setCancelable(false)
						.setTitle("提示")
						.setMessage(hanldResult(finaId))
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										postResult(
												PhoneInfoUtils
														.getIMEI(getApplicationContext()),
												rMB);
										dialog.cancel();
										PromotionRichActivity.this.finish();
									}
								}).create();
				alertbBuilder.show();
				// Toast.makeText(PromotionRichActivity.this, "中奖完毕",
				// Toast.LENGTH_SHORT).show();
				if (fruit <= 3) {
					// playSound(2,0);//声音
				}
			default:
				break;
			}
		};
	};

	/**
	 * 
	 * 方法说明：发送抽奖结果给服务器
	 * 
	 * @param biaozhifu
	 *            手机唯一识别码
	 * @param result
	 *            抽奖结果（1角对应 0.1）
	 */
	private void postResult(String biaozhifu, String result) {
		ProtocolService.putRMB(biaozhifu, result,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getApplicationContext(),
								R.string.phone_verify_send_fail);
					}
				});
	}

	/**
	 * 
	 * 方法说明：对抽奖最好结果进行处理
	 * 
	 * @param x
	 * @return
	 */
	private String hanldResult(int x) {
		switch (x) {
		case 6:
		case 10:
			// 1角
			rMB = "0.1";
			hint = "恭喜您抽到了 1  角";
			break;
		case 7:
		case 9:
			// 2角
			rMB = "0.2";
			hint = "恭喜您抽到了 2  角";
			break;
		case 2:
			// 4角
			rMB = "0.4";
			hint = "恭喜您抽到了 4  角";
			break;
		case 0:
			// 5角
			rMB = "0.5";
			hint = "恭喜您抽到了 5  角";
			break;
		case 3:
			// 10角
			rMB = "1.0";
			hint = "恭喜您抽到了 1 元";
			break;
		case 4:
			// 80角
			rMB = "8.0";
			hint = "恭喜您抽到了 8  元";
			break;
		default:
			// 谢谢参与
			rMB = "0.0";
			hint = "亲:\n\t谢谢参与！\n\t明天再来哦！";
			break;
		}
		return hint;

	}

	/**
	 * 计算出距离中奖还要走几步
	 * 
	 * @param sum
	 * @return
	 */
	public int checkfruit() {
		int i = 0;
		if (fruit == 1) {
			i = fruit1;
		} else if (fruit == 2) {
			i = fruit2;
		} else if (fruit == 3) {
			i = fruit3;
		} else {
			i = (int) (Math.random() * 100);
			i = i % image_num;
			if (i == fruit1) {
				i--;
			}
			if (i == fruit2) {
				i--;
			}
			if (i == fruit3) {
				i--;
			}
		}
		i += image_num;
		i = i - sum % image_num;
		if (i < 12) {
			i += image_num;
		}
		i = i + 1;
		// Log.i("计算再走几步", "当前图片编号+"+sum%image_num+" ;计算剩余步数："+(i+5));
		return i;
	}

	protected void ChangeImage(int sum) {
		int sum_2 = (sum % image_num);// 取余
		if (sum_2 == 0) {
			fruit_3.setImageResource(R.drawable.shade);
			fruit_2.setImageResource(R.drawable.xiexiecan);
		} else if (sum_2 == 1) {
			fruit_4.setImageResource(R.drawable.shade);
			fruit_3.setImageResource(R.drawable.wujiao);
		} else if (sum_2 == 2) {
			fruit_5.setImageResource(R.drawable.shade);
			fruit_4.setImageResource(R.drawable.xieixe);
		} else if (sum_2 == 3) {
			fruit_12.setImageResource(R.drawable.shade);
			fruit_5.setImageResource(R.drawable.sijiao);
		} else if (sum_2 == 4) {
			fruit_6.setImageResource(R.drawable.shade);
			fruit_12.setImageResource(R.drawable.yiyuan);
		} else if (sum_2 == 5) {
			fruit_8.setImageResource(R.drawable.shade);
			fruit_6.setImageResource(R.drawable.bbbb);
		} else if (sum_2 == 6) {
			fruit_1.setImageResource(R.drawable.shade);
			fruit_8.setImageResource(R.drawable.xieixea);
		} else if (sum_2 == 7) {
			fruit_11.setImageResource(R.drawable.shade);
			fruit_1.setImageResource(R.drawable.yyyy);
		} else if (sum_2 == 8) {
			fruit_9.setImageResource(R.drawable.shade);
			fruit_11.setImageResource(R.drawable.erjiao);
		} else if (sum_2 == 9) {
			fruit_10.setImageResource(R.drawable.shade);
			fruit_9.setImageResource(R.drawable.xieixea);
		} else if (sum_2 == 10) {
			fruit_7.setImageResource(R.drawable.shade);
			fruit_10.setImageResource(R.drawable.erjiao);
		} else if (sum_2 == 11) {
			fruit_2.setImageResource(R.drawable.shade);
			fruit_7.setImageResource(R.drawable.yyyy);
		}
		finaId = sum_2;
		// else if(sum_2==12){
		// fruit_12.setImageResource(R.drawable.banner_dian_focus);
		// fruit_11.setImageResource(R.drawable.erjiao);
		// }
	}

	/*
	 *//**
	 * 检测选中的奖项
	 * 
	 * @return
	 */
	// public int check_group_select() {
	// RadioButton button = (RadioButton) findViewById(award_group
	// .getCheckedRadioButtonId());
	// if (button.getText().equals("1等奖")) {
	// return 1;
	// } else if (button.getText().equals("2等奖")) {
	// return 2;
	// } else if (button.getText().equals("3等奖")) {
	// return 3;
	// } else {
	// return 0;
	// }
	// }
	/**
	 * 将控制图片变动做一个可控线程
	 * 
	 * @description
	 * @author 季佳满 2014-10-30上午9:58:51
	 * 
	 */
	private class ChangeThread extends Thread {
		private boolean stopFlag = false;

		@Override
		public void run() {
			while (!stopFlag) {
				try {
					if (!stopFlag) {
						for (int i = 0; i < StartUp.length; i++) {// 先执行启动
							sum++;
							Message message = new Message();
							message.what = CHANGIMAGE;
							Bundle bundle = new Bundle();
							bundle.putInt("imageid", sum);
							message.setData(bundle);
							handler.sendMessage(message);
							sleep(StartUp[i]);
						}
					}
					if (!stopFlag) {
						while (scrolling) {// 一直执行匀速变化
							sum++;
							Message message = new Message();
							message.what = CHANGIMAGE;
							Bundle bundle = new Bundle();
							bundle.putInt("imageid", sum);
							message.setData(bundle);
							handler.sendMessage(message);
							sleep(50);
						}
					}
					if (!stopFlag) {
						// 得到fruit值之后，开始停止计算一下当前走到哪里，并依照获奖结果停止到指定图片
						int m = checkfruit();
						// int m= 1;
						for (int i = 0; i < m; i++) {
							sum++;
							Message message = new Message();
							message.what = CHANGIMAGE;
							Bundle bundle = new Bundle();
							bundle.putInt("imageid", sum);
							message.setData(bundle);
							handler.sendMessage(message);
							sleep(50);
						}
						for (int i = 0; i < Moreover.length; i++) {
							sum++;
							Message message = new Message();
							message.what = CHANGIMAGE;
							Bundle bundle = new Bundle();
							bundle.putInt("imageid", sum);
							message.setData(bundle);
							handler.sendMessage(message);
							sleep(Moreover[i]);
						}
						for (int i = 0; i < Finish.length; i++) {
							sum++;
							Message message = new Message();
							message.what = CHANGIMAGE;
							Bundle bundle = new Bundle();
							bundle.putInt("imageid", sum);
							message.setData(bundle);
							handler.sendMessage(message);
							sleep(Finish[i]);
						}
						Message message1 = new Message();
						message1.what = CHANGSTARTBUT;
						handler.sendMessage(message1);
						stopFlag = true;
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					stopFlag = true;
				}
			}
		}

		public void stopThread() {
			stopFlag = true;
		}
	}
}
